package app.modules.cloudpivot.test;

import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.authine.cloudpivot.EnginePool;
import com.authine.cloudpivot.IEngine;
import com.authine.cloudpivot.engine.open.OpenEngine;
import com.authine.cloudpivot.engine.open.OpenEngineFactory;
import com.authine.cloudpivot.request.RequestContext;
import com.authine.cloudpivot.request.RequestInfo;
import com.authine.cloudpivot.web.api.controller.base.BaseController;

public class TenantThrealCase extends BaseController {
    private static final int CORE_POOL_SIZE = 30;
    private static final int MAX_POOL_SIZE = 50;
    private static final long KEEP_ALIVE_TIME = 60L;
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(200), new ThreadPoolExecutor.CallerRunsPolicy());

    public void demo() {
        /* 获取开放式引擎 */
        OpenEngine openEngine = OpenEngineFactory.getOpenEngine();

        /* 获取租户级JdbcTemplate */
        openEngine.getJdbcTemplate();

        /* 获取当前用户ID */
        RequestContext.getInstance().getRequestInfo().getUserId();

        /* 这是拿到所有的租户的IEngine对象 */
        Set<IEngine> engines = EnginePool.instance.getEngineSet();
        engines.stream().forEach(e -> {
            System.out.println("租户CODE：" + e.getEngineCode());
        });

        /* 这是根据租户CODE获取某一个租户的IEngine对象 */
        IEngine engine = EnginePool.instance.getEngine("租户CODE");

        /* 这是获取当前请求租户的IEngine对象 */
        IEngine current = RequestContext.getInstance().getEngine();

        executor.execute(() -> {
            try {
                /* 设置上下文信息 */
                RequestInfo request = RequestInfo.valueOf(current.createCommand(), "用户ID", "租户CODE");
                RequestContext.setRequestContextLocal(engine, request);
                /* FIXME 这里执行你的业务代码 */

            } finally {
                /* 必须清理上下文 */
                RequestContext.clearRequestContextLocal();
            }
        });
    }
}
